package com.bluefox.modules.quartz.service.impl;

import com.bluefox.exception.BadRequestException;
import com.bluefox.utils.PageUtil;
import com.bluefox.utils.QueryHelp;
import com.bluefox.modules.quartz.domain.QuartzJob;
import com.bluefox.modules.quartz.domain.QuartzLog;
import com.bluefox.modules.quartz.repository.QuartzJobRepository;
import com.bluefox.modules.quartz.repository.QuartzLogRepository;

import com.bluefox.modules.quartz.service.QuartzJobService;
import com.bluefox.modules.quartz.service.dto.JobQueryCriteria;
import com.bluefox.modules.quartz.utils.QuartzManage;
import com.bluefox.utils.RedisUtils;
import org.quartz.CronExpression;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName QuartzJobServiceImpl
 * @Description QuartzJobServiceImpl
 * @Author SunFeng
 * @Date 2020/2/28 15:32
 * @Version 1.0
 */
@Service(value = "quartzJobService")
@CacheConfig(cacheNames = "quartzJob")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class QuartzJobServiceImpl implements QuartzJobService {


    private final String REDIS_KEY_PREFIX="quartzJob::id:";

    private final QuartzJobRepository quartzJobRepository;

    private final QuartzLogRepository quartzLogRepository;

    private final QuartzManage quartzManage;

    private final RedisUtils redisUtils;

    public QuartzJobServiceImpl(QuartzJobRepository quartzJobRepository, QuartzLogRepository quartzLogRepository, QuartzManage quartzManage, RedisUtils redisUtils) {
        this.quartzJobRepository = quartzJobRepository;
        this.quartzLogRepository = quartzLogRepository;
        this.quartzManage = quartzManage;
        this.redisUtils = redisUtils;
    }

    @Override
    public Object queryAll(JobQueryCriteria criteria, Pageable pageable) {
        return PageUtil.toPage(quartzJobRepository.findAll((Specification<QuartzJob>) (root, query, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable));
    }

    @Override
    public List<QuartzJob> queryAll(JobQueryCriteria criteria) {
        return null;
    }

    @Override
    public Object queryAllLog(JobQueryCriteria criteria, Pageable pageable) {
        return null;
    }

    @Override
    public List<QuartzLog> queryAllLog(JobQueryCriteria criteria) {
        return null;
    }

    @Override
    @CachePut(key = "'id:'+#quartzJob.id")
    @Transactional(rollbackFor = Exception.class)
    public QuartzJob create(QuartzJob quartzJob) {
        if (!CronExpression.isValidExpression(quartzJob.getCronExpression())) {
            throw new BadRequestException("cron表达式格式错误");
        }
        quartzJob = quartzJobRepository.save(quartzJob);
        // 每次都需要将任务添加到定时任务管理器中
        quartzManage.addJob(quartzJob);
        return quartzJob;
    }

    @Override
    @CachePut(key = "'id:'+#quartzJob.id")
    @Transactional(rollbackFor = Exception.class)
    public QuartzJob update(QuartzJob quartzJob) {
        if (quartzJob.getId().equals(1L)) {
            throw new BadRequestException("该任务不可操作");
        }
        // 对Cron表达式进行验证
        if (!CronExpression.isValidExpression(quartzJob.getCronExpression())) {
            throw new BadRequestException("cron表达式格式错误");
        }
        quartzJob = quartzJobRepository.save(quartzJob);
        quartzManage.updateJobCron(quartzJob);
        return quartzJob;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        // 删除需要将数据库中的数据删除 还有工作管理器中的人物删除
        for (Long id : ids) {
            if (id.equals(1L)) {
                throw new BadRequestException("更新访客记录不可删除，你可以在后台代码中取消该限制");
            }
            QuartzJob quartzJob = quartzJobRepository.findById(id).orElse(new QuartzJob());
            quartzManage.deleteJob(quartzJob);
            quartzJobRepository.deleteById(id);
            for (int i = 0; i < ids.length; i++) {
                redisUtils.del(REDIS_KEY_PREFIX+ ids[i]);
            }
        }
    }

    @Override
    @Cacheable(key = "'id:'+#id")
    public QuartzJob findById(Long id) {
        System.out.println("走了数据库");
        return quartzJobRepository.findById(id).orElseGet(QuartzJob::new);
    }

    @Override
    @CachePut(key = "'id:'+#quartzJob.id")
    @Transactional
    public QuartzJob updateIsPause(QuartzJob quartzJob) {
       /* if(quartzJob.getId().equals(1L)){
            throw new BadRequestException("该任务不可操作");
        }*/
        //是暂停
        if (quartzJob.getIsPause()) {
            //开启作业
            quartzManage.resumeJob(quartzJob);
            //设置开启状态
            quartzJob.setIsPause(false);
        } else {
            quartzManage.pauseJob(quartzJob);
            quartzJob.setIsPause(true);
        }
        //将job进行更新
        return quartzJobRepository.save(quartzJob);
    }

    @Override
    public void execution(QuartzJob quartzJob) {
        if (quartzJob.getId().equals(1L)) {
            throw new BadRequestException("该任务不可操作");
        }
        quartzManage.runJobNow(quartzJob);
    }

    @Override
    public void download(List<QuartzJob> queryAll, HttpServletResponse response) throws IOException {

    }

    @Override
    public void downloadLog(List<QuartzLog> queryAllLog, HttpServletResponse response) throws IOException {

    }
}
